package com.dikeleakagedetection.myapplication.ui.ble

import android.bluetooth.BluetoothGattService
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.clj.fastble.data.BleDevice
import com.dikeleakagedetection.myapplication.R
import java.util.*

class ServiceAdapter(
    val context: Context,
    private val serviceList: List<BluetoothGattService>,
    private val bleDevice: BleDevice
) : RecyclerView.Adapter<ServiceAdapter.ViewHolder>() {

    //标记character是否展开的标记位
    private var isOpen = -1

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val tvServiceTitle: TextView = view.findViewById(R.id.tv_service_title)
        val tvServiceUUID: TextView = view.findViewById(R.id.tv_service_uuid)
        val tvServiceType: TextView = view.findViewById(R.id.tv_service_type)
        val lyServiceContent: LinearLayout = view.findViewById(R.id.ly_service_content)
        val rvChara: RecyclerView = view.findViewById(R.id.rv_chara)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(context).inflate(
            R.layout.item_service_frag_ble_service,
            parent,
            false
        )

        val holder = ViewHolder(view)
        val manager = LinearLayoutManager(holder.rvChara.context)
        holder.rvChara.layoutManager = manager

        return holder
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val service = serviceList[position]

        val name = "服务($position)"
        val uuid: UUID = service.uuid
        val type: String = service.type.toString()
        holder.tvServiceTitle.text = name
        holder.tvServiceUUID.text = uuid.toString()
        holder.tvServiceType.text = type

        val characterList = serviceList[position].characteristics
        val characteristicAdapter = CharacterAdapter(context, characterList, bleDevice)
        holder.rvChara.adapter = characteristicAdapter

        holder.itemView.setOnClickListener {
            if (isOpen == holder.adapterPosition) {
                //当点击的item已经被展开了, 就关闭.
                isOpen = -1
                notifyItemChanged(holder.adapterPosition)
            } else {
                val oldisOpen = isOpen
                isOpen = holder.adapterPosition
                notifyItemChanged(oldisOpen)
                notifyItemChanged(isOpen)
            }
        }

        if (isOpen == position) {
            holder.lyServiceContent.visibility = View.VISIBLE
        } else {
            holder.lyServiceContent.visibility = View.GONE
        }


    }

    override fun getItemCount() = serviceList.size

}